<template>
    <div class="container_box">
        <el-scrollbar class="main_box">
            <div class="content">
                <el-form
                    ref="formRef"
                    label-width="120px"
                    :model="formData"
                    :rules="rules"
                    :disabled="pageType == 'look'">
                    <div class="top">
                        <el-form-item label="所属分组" prop="group_id">
                            <el-cascader
                                ref="cascaderRef"
                                v-model="formData.group_id"
                                style="width: 100%"
                                :props="defaultProps"
                                :options="groupOptions"
                                @change="orgChange" />
                        </el-form-item>
                        <el-form-item label="活动标题" prop="title">
                            <el-input
                                v-model="formData.title"
                                placeholder="请输入活动标题"
                                maxlength="15"
                                :clearable="true"
                                class="input_icon"
                                show-word-limit></el-input>
                        </el-form-item>
                        <el-form-item label="活动有效期" class="period_type">
                            <el-radio-group v-model="formData.period_type">
                                <el-radio :label="1">永久</el-radio>
                                <el-radio :label="2">自定义期限</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item v-if="formData.period_type == 2" prop="activity_time">
                            <el-date-picker
                                v-model="formData.activity_time"
                                style="width: 100%"
                                type="datetimerange"
                                format="YYYY-MM-DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                range-separator="—"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                prefix-icon="Calendar"
                                :disabled-date="time => time.getTime() < Date.now() - 8.64e7">
                            </el-date-picker>
                        </el-form-item>
                    </div>
                    <el-form-item label="选择群聊" prop="groupchat_id">
                        <div>
                            <template v-if="formData.groupchat_id">
                                <div class="groupchat">
                                    <el-image
                                        v-if="groupInfo.avatar"
                                        :src="groupInfo.avatar"
                                        fit="cover"
                                        class="group_img">
                                        <template #error>
                                            <el-icon><icon-picture /></el-icon>
                                        </template>
                                    </el-image>
                                    <div>群名称：{{ groupInfo.name }}</div>
                                    <div>群主：{{ groupInfo.manager?.name }}</div>
                                </div>
                                <div class="groupchat_desc">
                                    选择1个群聊做为初始群聊，群满之后会自动创建新的群聊，无需担心群满的情况
                                </div>
                            </template>
                            <el-button @click="showGroupBox"
                                >{{ formData.groupchat_id ? '更换' : '选择' }}群聊</el-button
                            >
                        </div>
                    </el-form-item>
                    <el-form-item
                        label="入群打标"
                        label-width="130px"
                        prop="tag_list"
                        :rules="[
                            {
                                required: formData.tag_flag == 1 ? true : false,
                                message: '请选择入群打标',
                                trigger: 'blur'
                            }
                        ]">
                        <div class="switch_box">
                            <el-switch v-model="formData.tag_flag" :active-value="1" :inactive-value="2" />
                            <p class="text">打开后，针对老客户的入群的场景标记客户标签</p>
                        </div>
                        <div v-show="formData.tag_flag == 1" class="zw-el-tags">
                            <el-tag
                                v-for="tag in AllTags"
                                :key="tag"
                                class="tagsItem"
                                :closable="pageType !== 'look'"
                                @close="onClose1(tag)">
                                {{ tag.name }}
                            </el-tag>
                        </div>
                        <div class="add_tag_btn">
                            <el-button v-show="formData.tag_flag == 1" @click="selecTag">选择标签</el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </div>
            <GroupChart ref="GroupChartRef" :is-not-name-disabled="true" @submit="getGroupFun" />
            <BatchLabel ref="BatchLabelRef" @save="getTags" />
        </el-scrollbar>
        <div class="footer_box">
            <el-button @click="backHandle">取消</el-button>
            <el-button type="primary" @click="onSubmit">保存</el-button>
        </div>
    </div>
</template>

<script setup lang="ts">
import GroupChart from '@/components/chart/GroupChart.vue';
import { getGroupList } from '@/api/concreation';
import { endTimeValidator } from '@/utils/validate';
import { createUnlimitedPull, lookUnlimitedPull } from '@/api/customer/groupManage/unlimitedPull';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useStore } from '@/store';
import BatchLabel from '@/components/BatchLabel.vue';
import { getSetionId } from '@/utils/utils';

import { useRoute, useRouter } from 'vue-router';
import { ref, onMounted, h } from 'vue';
const emit = defineEmits(['submit']);
const store = useStore();
const route = useRoute();
const router = useRouter();
const pageType = route.query.type;
const formRef: any = ref(null);
const AllTags: any = ref([]);
const BatchLabelRef = ref();
const cascaderRef: any = ref(null); // 选择分组ref
const formData = ref<any>({
    title: '',
    group_id: Number(route.query.group_id), //分组ID
    period_type: 1,
    activity_time: [], //活动有效期
    groupchat_id: '',
    tag_list: [],
    tag_flag: 1
});
const rules = {
    title: [{ required: true, message: '请输入活动标题', trigger: 'blur' }],
    group_id: [{ required: true, message: '请选择所属分组', trigger: 'change' }],
    period_type: [{ required: true, message: '请选择活动有效期类型', trigger: 'change' }],
    // tag_list: [{ required: true, message: '请选择入群打标', trigger: 'change' }],
    activity_time: [
        { required: true, message: '请选择活动有效期', trigger: 'change' },
        { validator: endTimeValidator, trigger: 'blur' }
    ],
    groupchat_id: [{ required: true, message: '请选择群聊', trigger: 'change' }]
};
const groupOptions = ref([]);
const defaultProps = {
    checkStrictly: true, // 是否严格的遵守父子节点不互相关联
    emitPath: false,
    multiple: false,
    label: 'name',
    value: 'id'
};
// 选择群聊
const GroupChartRef = ref<any>();
const groupInfo = ref<any>({});
const showGroupBox = () => {
    GroupChartRef.value.echoDataId = groupOptions.value;
    GroupChartRef.value.appDialog.visible = true;
    GroupChartRef.value.single = true;
};
const backHandle = () => {
    router.back();
};
const getGroupFun = (v: any) => {
    groupInfo.value = v;
    formData.value.groupchat_id = v.group_id;
};

const onSubmit = async () => {
    if (!formRef.value) return;
    await formRef.value.validate((valid: any, fields: any) => {
        if (valid) {
            createUnlimitedPull(formData.value).then((res: any) => {
                ElMessage.success(`${pageType ? '编辑成功' : '新建成功'}`);
                router.push({
                    path: '/customer/groupManage/unlimitedPull',
                    query: {
                        group_id: formData.value.group_id
                    }
                });
            });
        } else {
            ElMessage.warning(Object.values(fields)[0][0].message);
        }
    });
};

const onLook = () => {
    lookUnlimitedPull({ id: route.query.id }).then((res: any) => {
        AllTags.value = res.tag_list;
        formData.value = {
            id: res.id,
            title: res.title,
            group_id: res.group_id, //分组ID
            period_type: res.period_type,
            activity_time: [res.period_start, res.period_end], //活动有效期
            groupchat_id: res.cust_group_id,
            tag_flag: res.tag_flag,
            tag_list: getSetionId('id', res.tag_list)
        };
        groupInfo.value = {
            group_id: res.cust_group_id,
            name: res.cust_group_info.name,
            avatar: res.cust_group_info.avatar,
            manager: {
                name: res.owner_work_user_name
            }
        };
    });
};
const onClose1 = (tag: any) => {
    AllTags.value = AllTags.value.filter((item: any) => item.id != tag.id);
    formData.value.tag_list = getSetionId('id', AllTags.value);
};
// 打开选择标签
const selecTag = () => {
    BatchLabelRef.value.hasConditiion = false;
    BatchLabelRef.value.dialogData.labelChooseType = 2;
    BatchLabelRef.value.chooseDataArr = [...AllTags.value];
    BatchLabelRef.value.dialogVisible = true;
};
const getTags = (data: any) => {
    AllTags.value = data.data;
    formData.value.tag_list = getSetionId('id', data.data);
};

// 选择完之后立即关闭
const orgChange = () => {
    cascaderRef.value.togglePopperVisible();
};

onMounted(() => {
    getGroupList({ type: 28, name: '' }).then((res: any) => {
        groupOptions.value = res.data;
    });
    pageType && onLook();
});
</script>

<style lang="scss" scoped>
.content {
    padding: 24px;
}

.period_type {
    margin-bottom: 0;
}

.top {
    width: 500px;
}

.add_tag_btn {
    margin-top: 16px;
}

.input_icon {
    :deep(.el-input__suffix) {
        .el-input__validateIcon {
            display: none;
        }
    }
}

.groupchat {
    width: 800px;
    padding: 10px 100px 10px 24px;
    margin-bottom: 6px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: #fff;
    border: 1px solid #eaeaea;
    font-size: 14px;
    font-family: STHeitiSC-Light, STHeitiSC;
    font-weight: 300;
    color: #33302d;
    line-height: 14px;

    .group_img {
        width: 36px;
        height: 36px;
        font-size: 36px;
        display: grid;
        place-content: center;
    }
}

.groupchat_desc {
    height: 14px;
    margin-bottom: 16px;
    font-size: 12px;
    font-family: STHeitiSC-Light, STHeitiSC;
    font-weight: 300;
    color: #969696;
    line-height: 14px;
}

:deep(.el-image__inner) {
    width: 36px;
    height: 36px;
}

.switch_box {
    display: flex;
    align-items: center;
    color: #9a9a9a;
    font-size: 12px;

    .text {
        margin-left: 10px;
    }
}

.tagsItem {
    margin-right: 10px;
}
</style>
